package config

import (
	"awesomeTask/application/variable"
	"awesomeTask/system/echo"
	"awesomeTask/system/helper"
	"awesomeTask/system/kernel"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
)

var configJson map[string]interface{}
var configPath string = CurrentFile()
var configLocalPath string = configPath + "/config-local.json"

func InitConfig() (jsonConfig1 map[string]interface{}) {
	if configJson != nil {
		return configJson
	}
	if echo.CheckCmdParams(1, func(value string) bool {
		return value == "current"
	}) {
		configPath = strings.ReplaceAll(helper.GetCurrentRunningPath(), "awesomeTask", "awesome-task")
		initTemplate()
	}
	if echo.CheckCmdParams(2, func(value string) bool {
		return value == "master"
	}) {
		variable.IsMaster = true
	}
	if helper.CheckFileIsExist(configLocalPath) == false {
		helper.WriteFile(configLocalPath, helper.JsonEncode(make(map[string]string)), 0777)
	}
	data, err := ioutil.ReadFile(configPath + "/config.json")
	if err != nil {
		panic(err.Error())
	}
	jsonConfig := make(map[string]interface{})
	err1 := json.Unmarshal(data, &jsonConfig)
	if err1 != nil {
		panic(err1.Error())
	}

	configJson = jsonConfig
	configJson["configDir"] = configPath
	return jsonConfig
}

func PrintConfig() {
	InitConfig()
	fmt.Println(helper.FormatJsonStringfy(configJson))
}
func CurrentFile() string {
	_, file, _, ok := runtime.Caller(1)
	if !ok {
		panic(errors.New("Can not get current file info"))
	}
	return filepath.Dir(file)
}
func GetConfigByKey(keys string, fun ...func() interface{}) interface{} {
	config := InitConfig()
	list := strings.Split(keys, ".")
	for index, i := range list {
		if index == len(list)-1 {
			value, ok := config[i]
			if ok {
				return value
			}
			if fun[0] != nil {
				return fun[0]()
			}
			return nil
		}
		if _, ok := config[i]; !ok {
			return nil
		}
		config = config[i].(map[string]interface{})
	}
	return config
}
func GetConfigByKeyWithAlias(keys string) interface{} {
	config := InitConfig()
	list := strings.Split(keys, ".")
	list[len(list)-1] = "Alias" + list[len(list)-1]
	for index, i := range list {
		if index == len(list)-1 {
			if config[i] != nil {
				return config[i]
			} else {
				return config[strings.Replace(i, "Alias", "", 1)]
			}

		}
		config = config[i].(map[string]interface{})
	}
	return config
}

func SetConfigByKey(key string, value interface{}) {
	InitConfig()
	list := strings.Split(key, ".")
	if len(list) > 2 {
		if GetConfigByKey(key) == nil {
			return
		} else {
			localConfig := configJson
			for index, itemKey := range list {
				if index == len(list)-1 {
					localConfig[itemKey] = value
				} else {
					localConfig = localConfig[itemKey].(map[string]interface{})
				}
			}
		}
	} else {
		configJson[key] = value
		//jsonByte,_ :=json.Marshal(configJson)
	}
	jsonString := helper.FormatJsonStringfy(configJson)
	configPath := configPath + "/config.json"
	helper.WriteFile(configPath, jsonString, 0777)
}

func GetConfigByPath(path string) map[string]interface{} {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		panic(err.Error())
	}
	return helper.JsonDecode(string(data)).(map[string]interface{})
}
func MergeConfig(paths ...string) {
	InitConfig()
	for _, path := range paths {
		for key, params := range GetConfigByPath(path) {
			configJson[key] = params
		}
	}
	configJson["uniqueId"] = kernel.GetKernelDriver().GetMac() + ":" + strconv.Itoa(int(configJson["listenPort"].(float64)))
}
func initTemplate() {
	configPath += "/awesome-task/"
	mainConfigPath := configPath + "/config.json"
	if helper.CheckFileIsExist(mainConfigPath) == false {
		template := `
{
    "baiduSdkAk": "GSivRhw5SSMQopkqWtPnI7bCzqLze4Z9",
	"clientToken": "jjawesomeLocalToken",
	"configDir": "D:\\project\\go\\src\\awesome-task\\config",
	"currentPath": "C:/Users/zhaolijie/AppData/Local/Temp",
	"database": {
		"master": {
			"database": "awesometask",
			"driver": "mysql",
			"host": "awesomeTask-mysql",
			"password": "awesomeTaskpublic",
			"port": "3306",
			"user": "root"
		}
	},
	"ddsPath": "C:/Users/zhaolijie/AppData/Local/Temp/FileSystem/dds/",
	"listenIpAddress": "127.0.0.1",
	"listenPort": 9980,
	"location": {
		"address": "四川省成都市",
		"lat": "30.57899372",
		"lng": "104.07274727"
	},
	"logPath": "C:/Users/zhaolijie/AppData/Local/Temp/FileSystem/log/",
	"loger": {
		"instance": "FileLoger",
		"params": {
			"path": "/Filesystem/log/"
		}
	},
	"node": {
		"manager": {
			"ipAddress": "127.0.0.1",
			"port": "9915"
		},
		"slave": []
	},
	"nodePort": 9982,
	"projectPath": "C:/Users/zhaolijie/AppData/Local/Temp/FileSystem/project/",
	"publicIP": "118.112.177.51",
	"taskCommand": "php D:\\project\\php\\advanced\\yii tool/index",
	"toMaster": true,
	"uniqueId": "c0:3e:ba:10:23:d6:9980",
	"websocketListenPort": 9981,
	"workPath": "C:/Users/zhaolijie/AppData/Local/Temp"
}
`
		helper.WriteFile(mainConfigPath, template, 0777)
	}
	localConfigPath := configPath + "/config-local.json"
	localTemplate := `{
  "taskCommand": "php D:\\project\\php\\advanced\\yii tool/index",
  "toMaster": true,
  "listenPort": 9980,
  "listenIpAddress": "127.0.0.1",
  "clientToken": "jjawesomeLocalToken"
}
`
	if helper.CheckFileIsExist(localConfigPath) == false {
		helper.WriteFile(localConfigPath, localTemplate, 0777)
	}
}
